package com.speedydial;

import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.SimpleCursorAdapter;

import com.speedydial.persistence.MessageDbAdapter;

/**
 * Por ahora solo practicando el Activity
 * 
 * @author mario
 *
 */
public class Main extends ListActivity  {

	private static final int ACTIVITY_CREATE=0;
	
	private static final String TAG = "MainActivity";
	
	private MessageDbAdapter mDbHelper;
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.message_list);
        
        // setting the database routines
        mDbHelper = new MessageDbAdapter(this);
        mDbHelper.open();
        
        // anadiendo otros widgets
        Button jumpToBtn = (Button) findViewById(R.id.jumpBtn);
        jumpToBtn.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// because we are inside an inner class, we need to
				// get an instance of the outer class
				Intent flip = new Intent(Main.this, EditSMSForm.class);
				startActivityForResult(flip,ACTIVITY_CREATE);
			}
		});
        
        
        // por ahora comentamos la creacion de la base de datos
        fillData();
//        mDbHelper.close();
    }
    
    @Override
    protected void onResume() {
    	super.onResume();
    }
  
    @Override
    protected void onStop() {
    	super.onStop();
    } 

    private void fillData() {
    	
    	Log.i(TAG, "filling data");
    	
        // Get all of the notes from the database and create the item list
        Cursor c = mDbHelper.fetchAllNotes();
        startManagingCursor(c);

        String[] from = new String[] { MessageDbAdapter.KEY_TITLE };
        int[] to = new int[] { R.id.message };
        
        // Now create an array adapter and set it to display using our row
        SimpleCursorAdapter notes = new SimpleCursorAdapter(this, 
        		                           R.layout.list_item, c, from, to);
        
        // TODO: descomentar al momento de cambiar a ListActivity
        setListAdapter(notes);
    }
	
	@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        fillData();
    }
}
